package Homework_1123;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//用dom4j对文档进行增删改查
public class DOM4J {

	//声明文档对象
	private Document document;
	//声明文档路径
	private String xmlPath="resources/plays.xml";
	//声明代码块，创建解析器
	{
		SAXReader saxReader = new SAXReader();
		try {
			document=saxReader.read(xmlPath);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {

		DOM4J dom4j = new DOM4J();
		//调用增加信息的方法
		//dom4j.add();
		//删除信息
		//dom4j.delete();
		//修改信息
		dom4j.modify();
		dom4j.showInfo();
	}

	private void modify() {
		Element rootElement = document.getRootElement();
		List<Element> playElements = rootElement.elements();
		for (Element playElement : playElements) {
			if("001".equals(playElement.attributeValue("id"))) {
				playElement.element("name").setText("《琉璃美人煞》");
				playElement.element("starring").addText("   刘学义   白澍");
			}
		}
		saveXML();
		System.out.println("数据修改成功！");
	}

	private void delete() {
		Element rootElement = document.getRootElement();
		List<Element> playElements = rootElement.elements();
		for (Element playElement : playElements) {
			if("005".equals(playElement.attributeValue("id"))) {
				playElement.getParent().remove(playElement);
			}
		}
		saveXML();
		System.out.println("数据删除成功！");
	}

	private void add() {
		Element rootElement = document.getRootElement();
		//添加一个子元素play
		Element playElement = rootElement.addElement("play");
		playElement.addAttribute("id", "005");
		playElement.addElement("name").setText("锦衣之下");
		playElement.addElement("starring").setText("任嘉伦   谭松韵");
		playElement.addElement("director").setText("尹涛");
		playElement.addElement("type").setText("古装剧");
		//将添加的信息保存
		saveXML();
		System.out.println("数据更新完毕！");
	}

	private void saveXML() {
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		
		try {
			XMLWriter writer = new XMLWriter(new FileWriter(xmlPath), format);
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	//显示文档信息
	private void showInfo() {
		//先获取文档的根元素
		Element rootElement = document.getRootElement();
		//输出根元素的title属性
		System.out.println(rootElement.attributeValue("title"));
		//获取根元素下的所有play元素
		List<Element> playElements = rootElement.elements();
		for (Element playElement : playElements) {
			System.out.println("这部剧的id是："+playElement.attributeValue("id"));
			//获取play下的其他所有元素
			List<Element> elements = playElement.elements();
			for (Element element : elements) {
				System.out.println("\t"+element.getTextTrim());
			}
		}
	}

}
